import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";

Vue.use(Vuex);

export default new Vuex.Store({
  // 仓库存储数据
  state: {
    msg: "hello  我是vuex中state的数据",
    two: "hello world",
    count: 12,
    list: []
  },
  // 改数据
  mutations: {
    m1(state, n) {
      state.count += n;
    },
    m2(state, n) {
      state.count -= n;
    },
    // 获取
    m3(state, n) {
      state.count -= n;
    },
    mList(state, list) {
      state.list = list;
    },
    // 添加
    madd(state, obj) {
      state.list.push(obj);
    },
    // 删除
    mdel(state, id) {
      state.list = state.list.filter(item => item.id !== id)
    },
    // 全选
    mall(state) {
      state.list.forEach(item => {
        item.done = true
      })
    },
    // 全清除
    mnoall(state) {
      state.list.forEach(item => {
        item.done = false
      })
    }
  },
  // 处理异步函数
  actions: {
    a1(context, m) {
      context.commit("m3", m);
    },
    // context是一个对象，通过解构对象来获得里面的属性commit
    a1({
      commit
    }, m) {
      commit("m3", m);
    },
    aList({
      commit
    }) {
      axios.get("list.json").then(res => {
        console.log(res);
        commit("mList", res.data);
      });
    }
  },
  // 计算属性  初次使用会立即执行  有return
  getters: {
    g1(state) {
      return state.count;
    },
    // 共几条
    mlength(state) {
      return state.list.filter(item => item.done == false).length
    }
  },
  modules: {}
});
